﻿#if UNITY_EDITOR
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
using UnityEngine;
/// <summary>
/// 编辑器XLSX管理器
/// </summary>
public partial class ESF_Utility
{
    /// <summary>
    /// 加载XLSX文件
    /// </summary>
    /// <param name="_xlsxPath">xlsx文件路径</param>
    /// <returns>XLSX文件</returns>
    public static IWorkbook LoadWorkBook(string _xlsxPath)
    {
        IWorkbook workbook = null;

        using (FileStream fileStream = new FileStream(_xlsxPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            try
            {
                string ext = Path.GetExtension(_xlsxPath);
                ESF_FileExtAttribute xlsx = enESF_UnityFileExt.Xlsx.ESF_FirstAttribute<ESF_FileExtAttribute>();
                ESF_FileExtAttribute xls = enESF_UnityFileExt.Xls.ESF_FirstAttribute<ESF_FileExtAttribute>();
                if (xls.IsExt(ext))
                {
                    workbook = new HSSFWorkbook(fileStream);
                }
                else if (xlsx.IsExt(ext))
                {
#if UNITY_EDITOR_OSX
                    throw new Exception("xlsx is not supported on OSX.");
#else
                    workbook = new XSSFWorkbook(fileStream);
#endif
                }
                else
                {
                    throw new UnityException($"Wrong file=>{_xlsxPath}");
                }
            }
            catch (Exception err)
            {
                Debug.LogError($"Can't resolve file=>{_xlsxPath}=>{err.Message}");
            }
        }
        return workbook;
    }

    /// <summary>
    /// 解析Xlsx表架构
    /// </summary>
    /// <param name="_xlsx">xlsx表</param>
    public static ISheet GetSheet(ESF_CollectAsset_XLSX _xlsx)
    {
        IWorkbook workbook = LoadWorkBook(_xlsx.xlsxTableSchemaXmlConfig.xml.xlsxFilePath);
        return workbook.GetSheetAt(_xlsx.xlsxTableSchemaXmlConfig.xml.xlsxSheetIndex());
    }

    /// <summary>
    /// 解析Xlsx表架构
    /// </summary>
    /// <param name="_xlsxFilePath">xlsx表路径</param>
    /// <param name="_sheetIndex">Sheet表索引</param>
    public static ISheet GetSheet(string _xlsxFilePath, int _sheetIndex)
    {
        IWorkbook workbook = LoadWorkBook(_xlsxFilePath);
        return workbook.GetSheetAt(_sheetIndex);
    }
}
#endif
